<template>
  <div class="chart-content">
    <div class="title cursorPointer" @click="handleTitleClick">
      生产效率&故障率
    </div>
    <div class="wrap">
      <div class="left">
        <div class="sub-title">年度生产效率 & 产线故障率</div>
        <CustomChart
          ref="CustomChart1"
          v-if="option1.xAxis.data.length"
          class="chart"
          :option="option1"
          :enableClickOptions="['xAxis.category', 'seriesZoneSameWidthxAxis']"
          :defaultZoomPosition="{ xAxis: 'currentMonth' }"
          @active-xAxisLabel-change="handleXAxisCategroyChange1"
        />
        <div v-else class="no-data">暂无数据</div>
      </div>
      <div class="right">
        <div class="sub-title">月度生产效率 & 产线故障率</div>
        <CustomChart
          v-if="option2.xAxis.data.length"
          class="chart"
          :option="option2"
          :enableClickOptions="['xAxis.category', 'seriesZoneSameWidthxAxis']"
          :defaultZoomPosition="{ xAxis: 'notEmpty' }"
          @active-xAxisLabel-change="handleXAxisCategroyClick2"
        />
        <div v-else class="no-data">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import CustomChart from "../../components/CustomChart";
import { getDayProduceData } from "@/api/dashboard/blowIrriagtionSpinLineMonthly";
import { transformEmtyValue, toFix } from "@/utils/eam";
import { transform, getLastSerieData } from "./commom";
const colors2 = [
  {
    type: "linear",
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      {
        offset: 0,
        color: "#4CE1E1", // 0% 处的颜色
      },
      {
        offset: 1,
        color: "#32F5FF", // 100% 处的颜色
      },
    ],
  },
  {
    type: "linear",
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      {
        offset: 0,
        color: "#FF6A23", // 0% 处的颜色
      },
      {
        offset: 1,
        color: "#FFA432", // 100% 处的颜色
      },
    ],
  },
];
export default {
  name: "LeftChart1",
  components: { CustomChart },
  props: {
    lineItem: {
      type: Object,
      default: null,
    },
    monthProduceData: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      option1: {
        color: [
          {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#4CE1E1", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#32F5FF", // 100% 处的颜色
              },
            ],
          },
          {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#FF6A23", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#FFA432", // 100% 处的颜色
              },
            ],
          },
        ],
        grid: {
          top: 46,
          left: 60,
          bottom: 40,
          right: 60,
        },
        title: {
          text: "",
          left: 20,
          textStyle: {
            color: "#ffffff",
            fontSize: 14,
            fontWeight: 500,
            rich: {
              highlight1: {
                color: "#46fbff",
                fontSize: 14,
              },
              highlight2: {
                color: "#ff7d28",
                fontSize: 14,
              },
            },
          },
        },
        tooltip: {
          trigger: "axis",
          padding: [5, 10],
          axisPointer: {
            type: "shadow",
          },
          formatter(params) {
            return `${
              params[0].name
            }<br /><i class="tooltip-circle" style="background-color:${
              params[0].color.colorStops[0].color
            };"></i>${params[0].seriesName}：${transformEmtyValue(
              params[0].value,
              "-"
            )}%<br /><i class="tooltip-circle" style="background-color:${
              params[1].color.colorStops[0].color
            };"></i>${params[1].seriesName}：${transformEmtyValue(
              params[1].value,
              "-"
            )}%<br /><i class="tooltip-circle" style="background-color:#628de4;"></i>
            生产时长：${transform(params[0].data.produceMinutes, (v) =>
              toFix(v / 60, 2)
            )}h<br /><i class="tooltip-circle" style="background-color:#d9b169;"></i>
            实际产量：${transform(params[0].data.actualQty)}箱`;
          },
        },
        legend: {
          data: [{ name: "生产效率" }, { name: "产线故障率" }],
          right: 20,
          // top: "40%",
          // orient: "vertical",
          textStyle: {
            color: "#ffffff",
          },
        },
        dataZoom: [
          {
            type: "inside",
            startValue: 0,
            endValue: 5,
            xAxisIndex: 0,
            filterMode: "empty",
          },
          {
            type: "slider",
            startValue: 0,
            endValue: 5,
            bottom: "3%",
            top: "92%",
            xAxisIndex: 0,
            showDetail: false,
            borderColor: "rgba(167,183,204,0.45)",
            fillerColor: "rgba(167,183,204,0.2)",
            filterMode: "empty",
          },
        ],
        xAxis: {
          data: [],
          triggerEvent: true,
          axisLine: {
            lineStyle: {
              color: "#485073",
            },
          },
          axisLabel: {
            interval: 0,
            color: "rgba(255, 255, 255, 0.6)",
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          name: "",
          nameGap: 26,
          position: "left",
          splitLine: {
            show: true,
            lineStyle: {
              color: "#485073",
            },
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            color: "rgba(255, 255, 255, 0.6)",
            formatter(value) {
              return value + "%";
            },
            fontSize: 11,
            hideOverlap: true,
          },
          axisTick: {
            show: false,
          },
          splitNumber: 5,
          min: 0,
          max: function (value) {
            return value.max == -Infinity || value.max < 100 ? 100 : value.max;
          },
        },
        series: [
          {
            name: "生产效率",
            data: [],
            type: "line",
            connectNulls: true,
            label: {
              show: true,
              position: "top",
              formatter: "{c}%",
              fontSize: 11,
              color: "rgba(255, 255, 255, 0.75)",
            },
            markLine: {
              symbol: [],
              lineStyle: {
                type: "dashed",
                width: 1,
                color: "#04b255",
              },
              label: {
                formatter: "{c}%",
              },
              data: [
                {
                  name: "",
                  yAxis: 0,
                },
              ],
            },
          },
          {
            name: "产线故障率",
            data: [],
            type: "line",
            connectNulls: true,
            label: {
              show: true,
              position: "top",
              formatter: "{c}%",
              fontSize: 11,
              color: "rgba(255, 255, 255, 0.75)",
            },
            markLine: {
              symbol: [],
              lineStyle: {
                type: "dashed",
                width: 1,
                color: "#00CB5E",
              },
              label: {
                formatter: "{c}%",
              },
              data: [
                {
                  name: "",
                  yAxis: 3.5,
                },
              ],
            },
          },
        ],
      },
      option2: {
        color: colors2,
        grid: {
          top: 46,
          left: 60,
          bottom: 40,
          right: 60,
        },
        title: {
          text: "",
          left: 20,
          textStyle: {
            color: "#ffffff",
            fontSize: 14,
            fontWeight: 500,
            rich: {
              highlight1: {
                color: "#46fbff",
                fontSize: 14,
              },
              highlight2: {
                color: "#ff7d28",
                fontSize: 14,
              },
            },
          },
        },
        tooltip: {
          trigger: "axis",
          padding: [5, 10],
          axisPointer: {
            type: "shadow",
          },
          formatter(params) {
            return `${
              params[0].name
            }<br /><i class="tooltip-circle" style="background-color:${
              params[0].color.colorStops[0].color
            };"></i>${params[0].seriesName}：${transformEmtyValue(
              params[0].value,
              "-"
            )}%<br /><i class="tooltip-circle" style="background-color:${
              params[1].color.colorStops[0].color
            };"></i>${params[1].seriesName}：${transformEmtyValue(
              params[1].value,
              "-"
            )}%<br /><i class="tooltip-circle" style="background-color:#628de4;"></i>
            生产时长：${transform(params[0].data.produceMinutes, (v) =>
              toFix(v / 60, 2)
            )}h<br /><i class="tooltip-circle" style="background-color:#d9b169;"></i>
            实际产量：${transform(params[0].data.actualQty)}箱`;
          },
        },
        legend: {
          data: [{ name: "生产效率" }, { name: "产线故障率" }],
          right: 20,
          // top: "40%",
          // orient: "vertical",
          textStyle: {
            color: "#ffffff",
          },
        },
        dataZoom: [
          {
            type: "inside",
            startValue: 0,
            endValue: 5,
            xAxisIndex: 0,
            filterMode: "empty",
          },
          {
            type: "slider",
            startValue: 0,
            endValue: 5,
            bottom: "3%",
            top: "92%",
            xAxisIndex: 0,
            showDetail: false,
            borderColor: "rgba(167,183,204,0.45)",
            fillerColor: "rgba(167,183,204,0.2)",
            filterMode: "empty",
          },
        ],
        xAxis: {
          data: [],
          triggerEvent: true,
          axisLine: {
            lineStyle: {
              color: "#485073",
            },
          },
          axisLabel: {
            interval: 0,
            color: "rgba(255, 255, 255, 0.6)",
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          name: "",
          nameGap: 26,
          position: "left",
          splitLine: {
            show: true,
            lineStyle: {
              color: "#485073",
            },
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            color: "rgba(255, 255, 255, 0.6)",
            formatter(value) {
              return value + "%";
            },
            fontSize: 11,
            hideOverlap: true,
          },
          axisTick: {
            show: false,
          },
          splitNumber: 5,
          min: 0,
          max: function (value) {
            return value.max == -Infinity || value.max < 100 ? 100 : value.max;
          },
        },
        series: [
          {
            name: "生产效率",
            data: [],
            type: "line",
            connectNulls: true,
            label: {
              show: true,
              position: "top",
              formatter: "{c}%",
              fontSize: 11,
              color: "rgba(255, 255, 255, 0.75)",
            },
            markPoint: {
              symbol: "circle",
              symbolSize: 1,
              itemStyle: {
                color: "rgba(0,0,0,0)",
              },
              label: {
                position: "right",
                offset: [10, 0],
                color: colors2[0].colorStops[1].color,
              },
              data: [],
            },
            markLine: {
              symbol: [],
              lineStyle: {
                type: "dashed",
                width: 1,
                color: "#04b255",
              },
              label: {
                formatter: "{c}%",
              },
              data: [
                {
                  name: "",
                  yAxis: 0,
                },
              ],
            },
          },
          {
            name: "产线故障率",
            data: [],
            type: "line",
            connectNulls: true,
            label: {
              show: true,
              position: "top",
              formatter: "{c}%",
              fontSize: 11,
              color: "rgba(255, 255, 255, 0.75)",
            },
            markPoint: {
              symbol: "circle",
              symbolSize: 1,
              itemStyle: {
                color: "rgba(0,0,0,0)",
              },
              label: {
                position: "right",
                offset: [10, 0],
                color: colors2[1].colorStops[1].color,
              },
              data: [],
            },
            markLine: {
              symbol: [],
              lineStyle: {
                type: "dashed",
                width: 1,
                color: "#00CB5E",
              },
              label: {
                formatter: "{c}%",
              },
              data: [
                {
                  name: "",
                  yAxis: 3.5,
                },
              ],
            },
          },
        ],
      },
      activeMonthIndex: null, // 默认显示的横坐标
    };
  },
  methods: {
    async getData1() {
      if (!this.monthProduceData) {
        return;
      }

      try {
        const {
          yearSumProduceEfficiency,
          yearSumAbnormalRatio,
          monthDatas,
          standardProduceEfficiency,
        } = this.monthProduceData;

        let xAxisData = [];
        let seriesData1 = [];
        let seriesData2 = [];
        let maxDataValue = 0;
        monthDatas.forEach((ele) => {
          xAxisData.push({
            value: ele.produceMonth,
            ...ele,
          });
          seriesData1.push({
            value: ele.produceEfficiency,
            produceMonth: ele.produceMonth,
            produceMinutes: ele.produceMinutes,
            actualQty: ele.actualQty,
          });
          seriesData2.push({
            value: ele.abnormalRatio,
            produceMonth: ele.produceMonth,
            produceMinutes: ele.produceMinutes,
            actualQty: ele.actualQty,
          });

          if (ele.produceEfficiency > maxDataValue) {
            maxDataValue = ele.produceEfficiency;
          } else if (ele.abnormalRatio > maxDataValue) {
            maxDataValue = ele.abnormalRatio;
          }
        });

        this.option1.title.text = `年累计生产效率 {highlight1|${
          yearSumProduceEfficiency || 0
        }%}，年累计产线故障率 {highlight2|${yearSumAbnormalRatio || 0}%}`;
        this.option1.xAxis.data = xAxisData;
        this.option1.series[0].data = seriesData1;
        this.option1.series[0].markLine.data[0].yAxis =
          standardProduceEfficiency || 0;
        this.option1.series[1].data = seriesData2;

        // 每日生产效率趋势图的标准生产效率
        this.option2.series[0].markLine.data[0].yAxis =
          standardProduceEfficiency || 0;
      } catch (error) {
        this.option1.title.text = `年累计生产效率 {highlight1|0%}，年累计产线故障率 {highlight2|0%}`;
        this.option1.xAxis.data = [];
        this.option1.series[0].data = [];
        this.option1.series[0].markLine.data[0].yAxis = 0;
        this.option1.series[1].data = [];

        // 每日生产效率趋势图的标准生产效率
        this.option2.series[0].markLine.data[0].yAxis = 0;
        console.error(error);
      }

      this.$nextTick(() => {
        if (this.monthProduceData?.monthDatas?.length > 0) {
          if (this.activeMonthIndex == null) {
            // 高亮显示的月份，默认本月
            const currMonth = this.parseTime(new Date(), "{y}-{m}");
            this.activeMonthIndex = this.option1.xAxis.data.findIndex(
              (ele) => ele.value == currMonth
            );
          }
          this.$refs.CustomChart1 &&
            this.$refs.CustomChart1.updatexAxisLabelActives(
              this.activeMonthIndex
            );
        } else {
          this.getData2();
        }
      });
    },
    // 获取日生产数据
    async getData2(monthData) {
      try {
        if (!monthData) {
          throw "月份为空";
        }
        const { factoryDeptCode, lineCode } = this.lineItem.properties;
        const params = {
          factoryDeptCode,
          lineCode,
          produceMonth: monthData.produceMonth,
        };
        const res = await getDayProduceData(params);

        let xAxisData = [];
        let seriesData1 = [];
        let seriesData2 = [];
        let maxDataValue = 0;
        res.data.forEach((ele) => {
          xAxisData.push({
            value: ele.produceDate,
            ...ele,
          });
          seriesData1.push({
            value: ele.produceEfficiency,
            produceDate: ele.produceDate,
            produceMinutes: ele.produceMinutes,
            actualQty: ele.actualQty,
          });
          seriesData2.push({
            value: ele.abnormalRatio,
            produceDate: ele.produceDate,
            produceMinutes: ele.produceMinutes,
            actualQty: ele.actualQty,
          });

          if (ele.produceEfficiency > maxDataValue) {
            maxDataValue = ele.produceEfficiency;
          } else if (ele.abnormalRatio > maxDataValue) {
            maxDataValue = ele.abnormalRatio;
          }
        });

        this.option2.title.text = `月累计生产效率 {highlight1|${
          monthData.produceEfficiency || 0
        }%}，月累计产线故障率 {highlight2|${monthData.abnormalRatio || 0}%}`;
        this.option2.xAxis.data = xAxisData;
        this.option2.series[0].data = seriesData1;
        this.option2.series[1].data = seriesData2;
        // 尾部累计
        const lastSerieData1 = getLastSerieData(seriesData1);
        if (lastSerieData1) {
          this.option2.series[0].markPoint.data = [
            {
              name: "累计",
              yAxis: lastSerieData1.value,
              xAxis: lastSerieData1.produceDate,
              value: `累计: ${monthData.produceEfficiency || 0}%`,
            },
          ];
        } else {
          this.option2.series[0].markPoint.data = [];
        }
        const lastSerieData2 = getLastSerieData(seriesData2);
        if (lastSerieData2) {
          this.option2.series[1].markPoint.data = [
            {
              name: "累计",
              yAxis: lastSerieData2.value,
              xAxis: lastSerieData2.produceDate,
              value: `累计: ${monthData.abnormalRatio || 0}%`,
            },
          ];
        } else {
          this.option2.series[1].markPoint.data = [];
        }
      } catch (error) {
        this.option2.title.text = `月累计生产效率 {highlight1|0%}，月累计产线故障率 {highlight2|0%}`;
        this.option2.xAxis.data = [];
        this.option2.series[0].data = [];
        this.option2.series[1].data = [];
        this.option2.series[0].markPoint.data = [];
        this.option2.series[1].markPoint.data = [];
        console.error(error);
      }
    },
    // 点击title，跳转到“生产效率&故障率分析”页面
    handleTitleClick() {
      this.$router.push({
        name: "FailureRateAnalysis",
      });
    },
    // 点击横坐标的年月，显示当月的生产效率
    handleXAxisCategroyChange1(index) {
      if (index || index == 0) {
        this.activeMonthIndex = index;
        this.getData2(this.option1.xAxis.data[index]);
      } else {
        this.getData2();
      }
    },
    // 点击横坐标的年月日，跳转到“生产效率&故障率分析”页面，并携带产线和日期信息
    handleXAxisCategroyClick2(index) {
      const { lineName, factoryDeptName } = this.lineItem.properties;
      this.$router.push({
        name: "FailureRateAnalysis",
        params: {
          lineName,
          factoryDeptName,
          produceDate: this.option2.xAxis.data[index].value,
        },
      });
    },
  },
  watch: {
    monthProduceData: {
      handler() {
        this.getData1();
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
.chart-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .wrap {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .left {
    flex: 1;
    width: 50%;
    height: 100%;
    padding-right: 10px;
    display: flex;
    flex-direction: column;
  }

  .right {
    flex: 1;
    width: 50%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .chart {
    flex: 1;
  }
}
.cursorPointer {
  cursor: pointer;
}
</style>
